package demo.security.example.web.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * TimeInterceptor
 *
 * @author lidj
 * @date 2018-01-09
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {


    /**
     * controller里某个方法调用之前，该方法会被调用
     * @param httpServletRequest
     * @param httpServletResponse
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
        System.out.println("pre handle");
        System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
        System.out.println(((HandlerMethod)handler).getMethod().getName());
        httpServletRequest.setAttribute("startTime",System.currentTimeMillis());

        /**
         * 这个返回值决定了后面的方法以及controller里的是否执行
         */
        return true;
    }


    /**
     * controller 里某个方法处理之后，该方法会被调用
     * 但是抛出异常后，该方法就不会被调用了
     * @param httpServletRequest
     * @param httpServletResponse
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("post handle");
        Long startTime = (Long) httpServletRequest.getAttribute("startTime");
        System.out.println("time interceptor 耗时:"+(System.currentTimeMillis()-startTime));
    }

    /**
     * controller 里某个方法处理之后，不管那个方法是否抛出异常
     * 这个方法都会被调用
     * @param httpServletRequest
     * @param httpServletResponse
     * @param handler
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler, Exception e) throws Exception {
        System.out.println("afterCompletion");
        Long startTime = (Long) httpServletRequest.getAttribute("startTime");
        System.out.println("time interceptor 耗时:"+(System.currentTimeMillis()-startTime));
        System.out.println("exception is " + e);
    }
}
